//
//  XLWebSocketNetWorking.m
//  WebSocketTest
//
//  Created by tanqilong on 16/8/10.
//  Copyright © 2016年 tanqilong. All rights reserved.
//

#import "XLWebSocketNetWorking.h"
#import <SocketRocket/SRWebSocket.h>

@interface XLWebSocketNetWorking () <SRWebSocketDelegate>
@property (nonatomic,strong) SRWebSocket * websocket;
@property (nonatomic,strong) NSObject * param;
@property (nonatomic,copy) void(^connected)();
@property (nonatomic,assign) BOOL isOpen;
@property (nonatomic,strong) NSDate * updateDate; //更新时间
@end

@implementation XLWebSocketNetWorking

-(id)initWebSocketWithUrl:(NSString *)url Parameters:(NSObject *)param IndicatorView:(UIView *)view Connected:(void(^)())connected Message:(sucBlock)sucBlock CancelLoading:(cancelBlock)cancelBlock LoadingError:(errorBlock)errorBlock {
    self = [super init];
    if (self) {
        self.requestUrl = url;
    }
    return [self initWebSocketWithParameters:param IndicatorView:view Connected:connected Message:sucBlock CancelLoading:cancelBlock LoadingError:errorBlock];
}

-(id)initWebSocketWithParameters:(NSObject *)param IndicatorView:(UIView *)view Connected:(void(^)())connected Message:(sucBlock)sucBlock CancelLoading:(cancelBlock)cancelBlock LoadingError:(errorBlock)errorBlock {
    self = [super init];
    if (self) {
        self.connected = connected;
        self.sucBlock = sucBlock;
        self.errorBlock = errorBlock;
        self.cancelBlock = cancelBlock;
        self.requestUrl = [self getRequestUrl];
        _websocket = [[SRWebSocket alloc]initWithURL:[NSURL URLWithString:self.requestUrl]];
        _websocket.delegate = self;
        _param = param;
        //开启连接
        [_websocket open];
        _isOpen = YES;
    }
    return self;
}

#pragma mark -- websocketDelegate
-(void)webSocketDidOpen:(SRWebSocket *)webSocket {
    if (self.connected) {
        _connected();
    }
    if (self.param) {
        [self sendMessage:self.param];
    }
}

-(void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    if (_updateTime > 0) {
        //需要控制刷新时间
        if ((-[self.updateDate timeIntervalSinceNow]) < _updateTime) {
            return;
        }
        self.updateDate = [NSDate date];
    }
    [self sucBlockDo:message];
}

-(void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
    [self errorBlockDo:error];
}

//发送消息给服务器
-(void)sendMessage:(NSObject *)message {
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:message options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    [_websocket send:jsonStr];
}

-(void)reopen {
    if (_isOpen) {
        return;
    }
    _isOpen = YES;
    _websocket = [[SRWebSocket alloc]initWithURL:[NSURL URLWithString:self.requestUrl]];
    _websocket.delegate = self;
    [_websocket open];
}

-(void)close {
    if (!_isOpen) {
        return;
    }
    _isOpen = NO;
    [_websocket close];
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}

-(NSDate *)updateDate {
    if (!_updateDate) {
        _updateDate = [NSDate dateWithTimeIntervalSinceNow:-self.updateTime];
    }
    return _updateDate;
}

-(void)dealloc {
    NSLog(@"释放");
}

@end
